package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.ApplyInfoActivity;
import com.epfresh.supplier.activity.BaseStoreInfoActivity;
import com.epfresh.supplier.activity.WebAgentNoticeActivity;
import com.epfresh.supplier.adapter.AgentMyApplyViewBinder;
import com.epfresh.supplier.adapter.AgentMyRecordViewBinder;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.AgentMyApplyRecord;
import com.epfresh.supplier.entity.AgentMyRecord;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.SaveEntity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.WrapContentLinearLayoutManager;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Created by zzq on 2017/12/4.
 */
public class AgentMyApplyFragment extends BaseFragment {

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    AgentMyApplyViewBinder agentMyApplyViewBinder;
    LinearLayoutManager mManager;
    RecyclerView rv;
    int pageNum = 0;
    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }

    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqApplyRecord(pageNum + 1);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.e("myOnCreateView","______________");
        return inflater.inflate(R.layout.fragment_agent_record,
                container, false);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
                reqApplyRecord(0);
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_agent_record);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }
    AgentMyApplyRecord bean;
    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);

        initHeadView(v);
        rv = v.findViewById(R.id.rv_make_agent);
        mManager = new WrapContentLinearLayoutManager(getContext());

        rv.setLayoutManager(mManager);
        mMultiAdapter = new MultiTypeAdapter();
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);
        agentMyApplyViewBinder = new AgentMyApplyViewBinder();
        agentMyApplyViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                Intent intent;
                if(data instanceof AgentMyApplyRecord)
                    bean = (AgentMyApplyRecord)data;
                switch (view.getId()){
                    case R.id.tv_agent_apply_again:
                        intoApplyAgent(bean.getId());
                        //T.toast("again");
                        break;
                    case R.id.tv_agent_apply_go:
                        intent = new Intent(getContext(), BaseStoreInfoActivity.class);
                        intent.putExtra("baseStoreId", bean.getId());
                        intent.putExtra("mHasAgent",false);
                        startActivity(intent);
                        break;
                }
            }
        });
        mMultiAdapter.register(AgentMyApplyRecord.class, agentMyApplyViewBinder);

        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rv.setAdapter(mMultiAdapter);
        mMultiAdapter.setItems(mItems);
        reqApplyRecord(pageNum);

    }
    private void intoApplyAgent(String mBaseStoreId) {

        if (mBaseStoreId != null && !"".equals(mBaseStoreId) && getContext() != null){
            SharedPreferences sp = getContext().getSharedPreferences("cache_config", Context.MODE_PRIVATE);
            boolean isRead = sp.getBoolean("config_read_agent_notice"+"_"+ ApplicationHelper.getInstance().getUser().getAccountId()+"_"+ BaseApplication.getInstance().getMerchantId(), false);

            if (!isRead) {
                Intent intent = new Intent(getContext(), WebAgentNoticeActivity.class);

                intent.putExtra("baseStoreId", mBaseStoreId);
                intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_HELP_AGENT_NOTICE);
                startActivity(intent);
            }else {
                Intent intent = new Intent(getContext(),ApplyInfoActivity.class);

                intent.putExtra("baseStoreId",mBaseStoreId);
                startActivityForResult(intent,0x1991);
            }
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    List<Object> mBaseStores = new ArrayList<>();

    public void reqApplyRecord(int pageNum) {
        if (getActivity() == null){
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_STORE_AGENT_LIST);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("pageSize", 15);
        int[] statuses = {1,3,6};
        RequestEntityMapSupply.putParameter("states",statuses);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_STORE_AGENT_LIST, onApplyRecordRequestListener);
    }

    private OnRequestListener<ContentEntity<AgentMyApplyRecord>> onApplyRecordRequestListener = new OnRequestListener<ContentEntity<AgentMyApplyRecord>>() {
        @Override
        public ContentEntity<AgentMyApplyRecord> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, AgentMyApplyRecord.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<AgentMyApplyRecord>> response, Object tag) {
            if (getActivity() == null){
                return;
            }
            ptrFrameLayout.refreshComplete();


            ContentEntity<AgentMyApplyRecord> responseElement = response.getResponseElement();


            boolean last = responseElement.getLast();

            int number = responseElement.getNumber();


            List<AgentMyApplyRecord> content = responseElement.getContent();

            //第一页
            if (number == 0) {
                mBaseStores.clear();
            }
            pageNum = number;
            if (content != null)
                mBaseStores.addAll(content);
            if(pageNum==0){
                mBaseStores.clear();
                mItems.clear();
            }
           mItems.addAll(content);
            Log.e("申请记录数据项",mItems.size()+"");

            if (mBaseStores.size() == 0) {
                loadMoreDelegate.addLoadItemOnly(mItems);
            }else {
                loadMoreDelegate.addAllItem(mItems, mBaseStores);
            }
            //最后一个
            if (last) {
                loadMoreDelegate.setStatusNoMore();
            } else {
                loadMoreDelegate.setStatusNormal();
            }
            mMultiAdapter.notifyDataSetChanged();

        }
    };

}
